package cn.z2huo.demo.spring.cloud.alibaba.consumer.controller;

import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

/**
 * <p>
 *
 * @author z2huo
 */
@RequiredArgsConstructor
@RestController
@RequestMapping("/consumer")
public class ConsumerController {

    @Autowired
    @Qualifier("restTemplate")
    private RestTemplate restTemplate;

    @Autowired
    private RestTemplate loadBalanceRestTemplate;

    private final LoadBalancerClient loadBalancerClient;

    @Value("${spring.application.name}")
    private String appName;

    @GetMapping("/consume")
    public void consume() {


    }

    @GetMapping("/loadBalance/echo/app-name")
    public String echoAppNameLoadBalance() {
        String url = String.format("http://alibaba-provider/provider/echo/%s", appName);
        System.out.println("request url:" + url);
        return loadBalanceRestTemplate.getForObject(url, String.class);
    }

    @GetMapping("/echo/app-name")
    public String echoAppName() {
        //使用 LoadBalanceClient 和 RestTemplate 结合的方式来访问
        ServiceInstance serviceInstance = loadBalancerClient.choose("alibaba-provider");
        String url = String.format("http://%s:%s/provider/echo/%s", serviceInstance.getHost(), serviceInstance.getPort(), appName);
        System.out.println("request url:" + url);
        return restTemplate.getForObject(url, String.class);
    }

}
